package com.zh.work.service.platform.channel.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.entity.Oauth;
import com.zh.common.util.IpAddressUtil;
import com.zh.work.dao.platform.channel.QrCodeChannelRouteMapper;
import com.zh.work.entity.ChannelRecordEntity;
import com.zh.work.entity.channel.QrCodeChannelRouteEntity;
import com.zh.work.entity.channel.QrCodeRouteMerchEntity;
import com.zh.work.service.platform.channel.QrCodeChannelRouteService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 二维码路由规则设置业务逻辑实现层
 * @Author: Li.HuiNeng
 * @Create in: 2019/09/04
 * @Version: 1.0.1
 */
@Service
public class QrCodeChannelRouteServiceImpl extends ServiceImpl<QrCodeChannelRouteMapper, QrCodeChannelRouteEntity> implements QrCodeChannelRouteService {

    @Autowired
    private QrCodeChannelRouteMapper mapper;

    @Qualifier("taskExecutor")
    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public IPage<QrCodeChannelRouteEntity> getChannelRoutePages(Page<QrCodeChannelRouteEntity> pages, QrCodeChannelRouteEntity routeEntity) {
        return this.mapper.selectPage(pages, new LambdaQueryWrapper<QrCodeChannelRouteEntity>()
                .eq(StringUtils.isNotEmpty(routeEntity.getBranchNo()), QrCodeChannelRouteEntity::getBranchNo, routeEntity.getBranchNo())
                .like(StringUtils.isNotEmpty(routeEntity.getRouteName()), QrCodeChannelRouteEntity::getRouteName, routeEntity.getRouteName())
                .eq(Objects.nonNull(routeEntity.getStatus()), QrCodeChannelRouteEntity::getStatus, routeEntity.getStatus())
                .like(StringUtils.isNotEmpty(routeEntity.getMerchNo()), QrCodeChannelRouteEntity::getMerchNo, routeEntity.getMerchNo())
        );
    }

    @Transactional
    @Override
    public int putQrCodeChannelRoute(QrCodeChannelRouteEntity routeEntity) throws Exception {
        // 先插入路由规则信息获取返回主键
        routeEntity.setTimeStart(routeEntity.getTimeStart().substring(0, 8));
        routeEntity.setTimeEnd(routeEntity.getTimeEnd().substring(0, 8));
        if (!routeEntity.insert()) return -1;
        Long id = routeEntity.getId();
        // 插入二维码路由商户信息
        List<QrCodeRouteMerchEntity> list = JSON.parseArray(routeEntity.getMerchantRouteJson(), QrCodeRouteMerchEntity.class);
        if (list.size() > 0) {
            list.forEach(f -> {
                f.setRouteId(id);
                try {
                    f.insert();
                } catch (MybatisPlusException e) {
                    e.printStackTrace();
                }
            });
        }
        return 1;
    }

    @Transactional
    @Override
    public int putModeChannelRqCodeRoute(QrCodeChannelRouteEntity routeEntity) throws Exception {
        routeEntity.setTimeStart(routeEntity.getTimeStart().substring(0, 8));
        routeEntity.setTimeEnd(routeEntity.getTimeEnd().substring(0, 8));
        // 查询数据库原值是否为空
        Map<String,Long> map = mapper.getQrCodeMerchantNum(routeEntity.getId());
        if (map.get("num") != 0) {
            // 先删除后添加
            if (mapper.delQrCodeRouteMerch(routeEntity.getId()) <= 0) return -1;
        }
        // 插入二维码路由商户信息
        List<QrCodeRouteMerchEntity> list = JSON.parseArray(routeEntity.getMerchantRouteJson(), QrCodeRouteMerchEntity.class);
        if (list.size() > 0) {
            list.forEach(f -> {
                f.setRouteId(routeEntity.getId());
                try {
                    f.insert();
                } catch (MybatisPlusException e) {
                    e.printStackTrace();
                }
            });
        }
        // 修改信息路由规则信息
        boolean b = routeEntity.updateById();
        if (!b) return -2;
        this.log(routeEntity, b);
        return 1;
    }

    @Override
    public int putChannelQrCodeStatus(QrCodeChannelRouteEntity routeEntity) {
        return mapper.updateById(routeEntity);
    }

    @Override
    public List<QrCodeRouteMerchEntity> getQrCodeMerchantByNo(Long id) {
        return mapper.getQrCodeMerchantByNo(id);
    }

    // 记录日志
    private void log(QrCodeChannelRouteEntity routeEntity, boolean result) {
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        this.taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ChannelRecordEntity channelRecordEntity = new ChannelRecordEntity();
                String ip = IpAddressUtil.getIpAddress(request);
                channelRecordEntity.setIp(ip);
                channelRecordEntity.setOperatorId(auth.getId());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                channelRecordEntity.setCreateTime(df.format(new Date()));
                channelRecordEntity.setRequestParam(JSON.toJSONString(routeEntity));
                List<QrCodeRouteMerchEntity> list1 = mapper.getQrCodeMerchantByNo(routeEntity.getId());
                channelRecordEntity.setBeforeValue(JSON.toJSONString(list1));
                channelRecordEntity.setRequestFunc("putModeChannelRqCodeRoute()");
                channelRecordEntity.setSuccess(result);
                channelRecordEntity.insert();
            }
        });
    }
}
